
/** innerAudio */
const useInnerAudio = () => {
	/** 音频实例 */
	let innerAudio: UniNamespace.InnerAudioContext = null;
	
	/** 创建 audio 上下文 innerAudio 对象 */
	const createInnerAudioContext = () => {
		if (!innerAudio) innerAudio = uni.createInnerAudioContext();
	};
	createInnerAudioContext();
	
	
	let onPlayCllaback: () => void = null;
	/** 音频播放事件 */
	const onPlay = (cllaback: () => void) => {
		if (typeof cllaback !== 'function') throw new Error(`${cllaback} is not a function`);
		onPlayCllaback = cllaback;
	};
	innerAudio.onPlay(() => {
		onPlayCllaback?.();
	});
	
	
	let onPauseCllaback: () => void = null;
	/** 音频暂停事件 */
	const onPause = (cllaback: () => void) => {
		if (typeof cllaback !== 'function') throw new Error(`${cllaback} is not a function`);
		onPauseCllaback = cllaback;
	};
	innerAudio.onPause(() => {
		onPauseCllaback?.();
	});
	
	
	let onStopCllaback: () => void = null;
	/** 音频停止事件 */
	const onStop = (cllaback: () => void) => {
		if (typeof cllaback !== 'function') throw new Error(`${cllaback} is not a function`);
		onStopCllaback = cllaback;
	};
	innerAudio.onStop(() => {
		onStopCllaback?.();
	});
	
	
	let onEndedCllaback: () => void = null;
	/** 音频自然播放结束事件 */
	const onEnded = (cllaback: () => void) => {
		if (typeof cllaback !== 'function') throw new Error(`${cllaback} is not a function`);
		onEndedCllaback = cllaback;
	};
	innerAudio.onEnded(() => {
		onEndedCllaback?.();
	});
	
	
	let onTimeUpdateCllaback: () => void = null;
	/** 音频播放进度更新事件 */
	const onTimeUpdate = (cllaback: () => void) => {
		if (typeof cllaback !== 'function') throw new Error(`${cllaback} is not a function`);
		onTimeUpdateCllaback = cllaback;
	};
	innerAudio.onTimeUpdate(() => {
		onTimeUpdateCllaback?.();
	});
	
	
	const stop = () => {
		if (!innerAudio.paused && innerAudio.src) {
			innerAudio.stop();
		};
	};
	
	const pause = () => {
		if (!innerAudio.paused && innerAudio.src) {
			innerAudio.pause();
		};
	};
	
	
	/** set audio src */
	const src = (url?: string) => {
		innerAudio.src = '';
		innerAudio.src = url;
		if (!url && innerAudio.src || innerAudio.src === url) innerAudio.seek(0);
		else innerAudio.src = url;
		innerAudio.paused && innerAudio.play();
	};
	
	return { 
		onPlay, onPause, onStop, onEnded, onTimeUpdate, src, stop, pause,
		play: innerAudio.play,
		source: innerAudio.src,
		paused: innerAudio.paused
	};
};


export default useInnerAudio;